package main

import (
	"flag"
	"os"
	"path"
	"strings"

	"xgame.go_server/biz_server/network/ws"
	"xgame.go_server/cluster"
	"xgame.go_server/comm/log"
)

var pServerId *int             // 服务器 Id
var pBindHost *string          // 绑定主机地址
var pBindPort *int             // 绑定端口号
var pSjtArray *string          // Sjt = (S)erver(J)ob(T)ype, 服务器职责类型数组
var pLogFile *string           // 日志文件
var pEtcdEndpointArray *string // ETCD 节点地址数组

//
// 初始化
func init() {
	ex, err := os.Executable()

	if nil != err {
		panic(err)
	}

	defultLogFile := path.Dir(ex) + "/log/biz_server.log"

	pServerId = flag.Int("server_id", 0, "业务服务器 Id")
	pBindHost = flag.String("bind_host", "127.0.0.1", "绑定主机地址")
	pBindPort = flag.Int("bind_port", 12345, "绑定端口号")
	pSjtArray = flag.String("server_job_type_array", "", "服务器职责类型数组")
	pLogFile = flag.String("log_file", defultLogFile, "日志文件")
	pEtcdEndpointArray = flag.String("etcd_endpoint_array", "127.0.0.1:2379", "Etcd 节点地址数组")
	flag.Parse()
}

//
// 应用程序主函数
func main() {
	// 配置日志
	log.Config(*pLogFile)

	// 启动服务器
	bootUp()
}

//
// 启动服务器
func bootUp() {
	log.Info(
		"启动业务服务器, serverId = %d, serverAddr = %s:%d, sjtArray = %s",
		*pServerId,
		*pBindHost,
		*pBindPort,
		*pSjtArray,
	)

	// 启动 WebSocket 服务器
	ws.StartServer(*pBindHost, *pBindPort, "/ws")

	ectdEndpointArray := strings.Split(*pEtcdEndpointArray, ",")
	sjtArray := cluster.StrToSjtArray(*pSjtArray)

	// 注册业务服务器
	cluster.RegisterBizServer(
		ectdEndpointArray,
		uint32(*pServerId), *pBindHost, uint32(*pBindPort), sjtArray,
	)

	// 阻塞程序, 使其不退出...
	syncWait := make(chan int16)
	<-syncWait
}
